import { defineStore } from 'pinia'
import axios from 'axios'

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null,
    isLoggedIn: false,
    token: localStorage.getItem('token') || null
  }),
  actions: {
    async checkLoginStatus() {
      if (!this.token) {
        this.isLoggedIn = false
        return false
      }

      try {
        const response = await axios.get('http://127.0.0.1:8888/user/info', {
          headers: { 'Authorization': `Bearer ${this.token}` }
        })
        
        this.userInfo = response.data
        this.isLoggedIn = true
        return true
      } catch (error) {
        console.error('登录状态检查失败:', error)
        this.logout()
        return false
      }
    },
    setToken(token) {
      this.token = token
      this.isLoggedIn = !!token
      localStorage.setItem('token', token)
    },
    logout() {
      this.token = null
      this.userInfo = null
      this.isLoggedIn = false
      localStorage.removeItem('token')
    }
  }
})
